package com.jianan.mis.service;

import java.math.BigDecimal;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Projections;

import com.jianan.mis.data.dao.DepartmentDao;
import com.jianan.mis.data.dao.OsDepartmentContractDao;
import com.jianan.mis.data.domain.Department;
import com.jianan.mis.data.domain.OsDepartmentContract;

public class DepartmentServiceImpl implements DepartmentService {

	private DepartmentDao departmentDao;

	private OsDepartmentContractDao osDepartmentContractDao;

	public void save(Department department) {
		departmentDao.save(department);
	}

	public void update(Department department) {
		departmentDao.saveOrUpdate(department);
	}

	public void remove(Department department) {
		departmentDao.remove(department);
	}

	public List<Department> getAll() {
		return departmentDao.getAll(Department.class, "Name", true);
	}
	
	public void findByName(String name) {
		departmentDao.findUniqueBy(Department.class, "Name", name);
	}

	public BigDecimal getRemainingDeposit(Integer departmentId) {
		BigDecimal totalDeposit = departmentDao.get(Department.class, departmentId).getTotalDeposit();
		Criteria criteria = osDepartmentContractDao.createCriteria(OsDepartmentContract.class);
		criteria.add(Expression.eq("Department.id", departmentId));
		criteria.setProjection(Projections.sum("SignupSum"));
		List result = criteria.list();
		BigDecimal signupSum = null;
		if (result.size() <= 0 || result.get(0) == null)
			signupSum = new BigDecimal(0);
		else
			signupSum = (BigDecimal) result.get(0);
		
		return totalDeposit.subtract(signupSum).setScale(2, BigDecimal.ROUND_HALF_UP);
	}

	public void setDepartmentDao(DepartmentDao departmentDao) {
		this.departmentDao = departmentDao;
	}

	public void setOsDepartmentContractDao(
			OsDepartmentContractDao osDepartmentContractDao) {
		this.osDepartmentContractDao = osDepartmentContractDao;
	}

}
